package hotel.action;

import java.util.List;

import hotel.model.IRequest;
import hotel.model.IRoom;
import hotel.service.RequestService;
import hotel.service.RoomService;
import hotel.service.ServiceManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
/**
 * This class accept request or send message than such rooms don't exist in DB
 * @author Alex
 *
 */
public class AcceptRequestAction extends Action 
{
	private static final Logger logger = Logger.getLogger(AcceptRequestAction.class);
	private static final String ACCEPTREQUESTACTION_ERROR = "Error in AcceptRequestAction:";
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest httpRequest, HttpServletResponse response)
		    throws Exception 
	{
		String mapper = ForwardActionTo.ERROR;
		try
		{
			IRequest request = null;
			List<IRoom> rooms = null;
			ActionMessages messages = new ActionMessages();
			int id;
					
			RequestService requestService = ServiceManager.getDefault().getRequestService();
			RoomService roomService = ServiceManager.getDefault().getRoomService();
			
			id = Integer.valueOf(httpRequest.getParameter("id"));
			request = requestService.getById(id);
			rooms = roomService.getRoomByRoomClassAndBeds(request.getBeds(), request.getRoomClass());
	
			if (rooms.isEmpty() == true)
			{
				messages.add("norooms", new ActionMessage("error.request.norooms"));
	   	 	 	saveMessages(httpRequest,messages);
				//message : no such rooms
	   	 	 	mapper = ForwardActionTo.SUCCESS;
			}
			else
			{
				try
				{
					roomService.updateRoom(rooms.get(0).getId(), request.getId());
					requestService.changeStatus(id, "accepted");
					messages.add("accept_success", new ActionMessage("request.accept.success"));
					saveMessages(httpRequest, messages);
				}
				catch(Exception e) 
				{
					
				}
				finally
				{
					mapper = ForwardActionTo.SUCCESS;
				}
			}
		}
		catch(NullPointerException e)
		{
			logger.error(ACCEPTREQUESTACTION_ERROR + e);
	 	}
		return mapping.findForward(mapper);
	}

}
